Linking related data in MongoDB can be achieved by using techniques such as embedding documents or referencing documents, depending on the structure and requirements of your application. Here's an overview of both approaches:
Store related data within the same document. This is useful for closely related data that is accessed together.
Fast and easy to access related data.
Reduces the need for joins or multiple queries.
Store related data in separate collections and reference them using unique identifiers
Keeps documents lightweight and scalable
Flexible for complex relationships
We have a users collection and a separate orders collection. How would you retrieve a user along with all their orders in a single query?
If you need to store a user's address that rarely changes, would you embed it in the user document or reference a separate addresses collection? Explain your choice.
Our product team wants to add a feature that shows the latest comment for each blog post. The comments are in a separate collection. Walk me through how you'd implement this, and what trade‑offs you consider.
During a recent deployment, a query that used $lookup started timing out. What steps would you take to diagnose and fix the performance issue?
We're designing a multi‑tenant SaaS platform where each tenant's data lives in shared collections but must be isolated. How would you model relationships (e.g., tenant → projects → tasks) to balance query performance and data security?
Explain how you would handle eventual consistency when you denormalize related data for read‑heavy workloads, and what mechanisms you would put in place to keep the copies in sync.
Our legacy system stores related entities using DBRefs, but we want to migrate to an embedding strategy for high‑traffic read paths without downtime. Outline a migration plan that minimizes risk and coordinates across teams.
At scale we see hot‑spotting on a heavily referenced document (e.g., a product catalog entry). What architectural changes would you propose to avoid write contention while still allowing fast lookups of related data?